<template>
	<view class="index-page with-tabbar" v-if="custom && loading">
		<!-- 1. 顶部自定义导航栏 -->
		<u-navbar v-if="!scrollPage" leftIcon="" :fixed="true" :safeAreaInsetTop="true" :bgColor="bgColor"
			:placeholder="true">
			<view class="u-nav-slot flex-center" slot="left">
				<div class="title pl-30  flex-center" style="width: 100vw;">
					<image src="https://xingangtong.oss-cn-beijing.aliyuncs.com/common/202506266zWSTa.png" class="logo"
						mode="aspectFill"></image>
				</div>
			</view>

		</u-navbar>
		<div class="navTop" :class="scrollPage ? 'navTopFix' : ''"
			:style="{ paddingTop: !scrollPage ? '0px' : custom.top + 'px', 'paddingBottom': custom.top - statusBarHeight + 'px', 'height': !scrollPage ? custom.height + 'px' : custom.height + custom.top + custom.top - statusBarHeight + 'px' }">
			<div class="flex-center searchContent">
				<div class="flex-center serchBox pr-6 pl-30  "
					:style="{ 'lineHeight': custom.height + 'px', 'height': custom.height + 'px', 'width': scrollPage ? 'calc(100% - ' + custom.width + 'px)' : 'calc(100% - 140upx)' }">
					<picker mode="region" @change="changeRegion">
						<view class="flex-center">
							<view class="form-label resume-title fontS28 color-3 fontE1" style="min-width: 60upx;"> {{
								region
							}} </view>

							<div class="ml-10 cuIcon-back " style="transform: rotate(-90deg);"></div>
						</view>
					</picker>
					<div class="searchInput ml-20">
						<input type="text" v-model="searchName" placeholder="请输入关键字">
					</div>
					<div class="ml-auto searchBtn color-fff text-center fontS24 "
						:style="{ 'lineHeight': custom.height - 6 + 'px', 'height': custom.height - 6 + 'px' }"
						@click="toSearch">
						搜索</div>
				</div>



				<div class="ml-auto flex flex-direction align-center" v-if="!scrollPage && userInfo.userType === '03'"
					@click="toggleRole('02')">
					<div class=" iconfont icon-qiehuan "></div>
					<div class="fontS24">去找工作</div>
				</div>
				<div class="ml-auto flex flex-direction align-center"
					v-else-if="!scrollPage && userInfo.userType !== '03'" @click="toggleRole('03')">
					<div class=" iconfont icon-qiehuan "></div>
					<div class="fontS24">一键企服</div>
				</div>
			</div>

		</div>


		<!-- 页面主要内容区域 -->
		<view class="page-content"
			:style="{ paddingTop: scrollPage ? custom.height + custom.top + custom.top + 'px' : '0' }">
			<!-- 2. 轮播图 Banner -->
			<view class="banner-section">
				<swiper class="banner-swiper" circular :indicator-dots="false" autoplay :current="currentBanner"
					@change="onBannerChange">
					<swiper-item v-for="(item, index) in bannerList" :key="index" @click="goDetail('banner', item)">
						<view class="swiper-item-container">
							<view class="swiper-item-wrapper">
								<image :src="baseUrl + item.imageUrl" class="banner-image" mode="aspectFill"></image>

							</view>
						</view>
					</swiper-item>
				</swiper>
				<!-- 自定义指示器 -->
				<view class="custom-indicator">
					<view v-for="(item, idx) in bannerList" :key="item.id"
						:class="['indicator-dot', { active: idx === currentBanner }]"></view>
				</view>
			</view>

			<!-- 3. 金刚区网格菜单 -->
			<view class="grid-menu-section mb-20">
				<swiper class="grid-swiper" :style="{ 'height': girdHeight + 'px' }" :indicator-dots="false"
					:current="currentGridPage" @change="onGridChange">
					<swiper-item v-for="(page, pageIndex) in menuPages" :key="pageIndex">
						<view class="grid">
							<view class="grid-item" v-for="(item, itemIndex) in page" :key="itemIndex"
								@click="goDetail('serve', item)">
								<image :src="baseUrl + item.imageUrl" class="grid-icon"></image>
								<text class="grid-text">{{ item.serveName }}</text>
							</view>
						</view>
					</swiper-item>
				</swiper>
				<!-- 自定义灰色指示器 -->
				<view class="custom-grid-indicator">
					<view v-for="(page, idx) in menuPages" :key="idx"
						:class="['grid-indicator-dot', { active: idx === currentGridPage }]"></view>
				</view>
			</view>


			<!-- 补贴申领 企业端 -->
			<view class="subsidy-company mb-20 flex-center justify-between lh-102 fontS28 font-500 "
				v-if="userInfo.userType === '03'">
				<div class="pl-25 pr-25 bor-r16" :style="{ 'background': item.bgColor, 'color': item.color }"
					v-for="(item, index) in subsidyList" :key="index" @click="goUrl(item)">
					{{ item.title }}

				</div>
			</view>
			<!-- 4. 补贴申领 Banner 牛人端  -->
			<view class="subsidy-banner" v-else @click="goSubsidy">
				<view class="subsidy-text">
					<text class="subsidy-title">补贴申领 (就业补贴、创业补贴)</text>
					<text class="subsidy-subtitle">社保补贴、住房租赁补贴、创业补贴等</text>
				</view>
				<uni-icons type="arrow-right" size="20" color="#3074FE"></uni-icons>
			</view>


			<!-- 牛人列表 -->
			<view class="job-list-section" v-if="userInfo.userType === '03'">
				<!-- 两级Tab结构 -->
				<view class="job-tabs-container">
					<!-- 主分类 -->
					<view class="main-tabs bor-b">
						<view class="tabs-scroll">
							<text v-for="(tab, index) in positionTabs" :key="tab.id" class="main-tab-item pb-20"
								:class="{ active: activeMainTab === index }" @click="selectMainTab(tab, index)">
								{{ tab.professionName }}
							</text>
						</view>
					</view>

					<!-- 子分类 (仅在当前主分类有 subTabs 时显示) -->
					<view class="sub-tabs">
						<view class="tabs-scroll">
							<text class="sub-tab-item active" @click="selectSubTab(subTab.id)">
								最新
							</text>
						</view>
						<view class="filter-button flex-center" @click="filterBtn">
							<div class="iconfont icon-shaixuan fontS30"></div>
							<div class="ml-10">筛选</div>
							<div v-if="filterParamNum">·{{ filterParamNum }}</div>
						</view>
					</view>
				</view>

				<view class="job-card" v-for="(job, index) in personList" :key="index" @click="goPersonDetail(job)">
					<view class="card-tops flex-center">
						<text class="job-title">{{ job.name }}</text>
						<text class="job-exper fontS24  color-80 ml-40">{{ job.experienceRequire || '' }}年 ｜ {{
							job.highEducationName || '' }} ｜ {{
								job.exceptSalary || '' }}</text>
					</view>

					<view class="card-tags" v-if="job.label">
						<text class="tag" v-for="tag in job.label.split(',')" :key="tag">{{ tag }}</text>
					</view>
					<view class="card-bottom mt-8">
						<view class="hr-info">
							<text class="hr-name fontS24 color-3"> {{ job.companyName || '' }} {{ job.companyName
								&& job.professionName ? '|' : '' }} {{ job.professionName || '' }}</text>
						</view>

					</view>
				</view>
				<view v-if="!noteComFlag && !loadList" class="pt-20 pb-20 color-6d text-center fontS28">没有更多数据</view>
				<without v-if="loadList"></without>

			</view>
			<!-- 5. 职位列表 -->
			<view v-else class="job-list-section">
				<!-- 两级Tab结构 -->
				<view class="job-tabs-container">
					<!-- 主分类 -->
					<view class="main-tabs">
						<view class="tabs-scroll">

							<text v-for="(tab, index) in jobTabs" :key="index" class="main-tab-item pb-20"
								:class="{ active: activeMainTab === index }" @click="selectMainTab(tab, index)">
								{{ tab.professionName }}
							</text>
						</view>
					</view>

					<!-- 子分类 (仅在当前主分类有 subTabs 时显示) -->
					<view class="sub-tabs">
						<view class="tabs-scroll">
							<text class="sub-tab-item active" @click="selectSubTab(subTab.id)">
								最新
							</text>
						</view>
						<view class="filter-button flex-center" @click="filterBtn">
							<div class="iconfont icon-shaixuan fontS30"></div>
							<div class="ml-10 ">筛选</div>
							<div v-if="filterParamNum">·{{ filterParamNum }}</div>
						</view>
					</view>
				</view>

				<view class="job-card" v-for="(job, index) in jobList" :key="index" @click="goJobDetail(job)">
					<view class="card-top">
						<text class="job-title">{{ job.professionName || '' }}</text>
						<text class="job-salary">{{ job.salary }}{{ job.salaryMonth ? '·' + job.salaryMonth + '薪' : ''
						}}</text>
					</view>
					<view class="card-company">
						<text>{{ job.companyName || '' }} {{ job.companySizeName || '' }}</text>
						<text class="card-company-location">{{ job.areaName || '' }}</text>
					</view>
					<view class="card-tags flex-center" v-if="job.postKey.length > 0">
						<div class="tag" v-for="tag in job.postKey.split(',')" :key="tag">{{ tag }}</div>
					</view>
					<view class="card-bottom">
						<view class="hr-info">
							<text class="hr-name">{{ job.creator || '' }}·{{ job.creatorPostName || '' }}</text>
						</view>
						<!-- <view class="online-status">
							<view class="dot"></view>
							<text>当前在线</text>
						</view> -->
					</view>
				</view>
				<view v-if="!noteFlag && !loadList" class="pt-20 pb-20 color-6d text-center fontS28">没有更多数据</view>
				<without v-if="loadList"></without>
			</view>
		</view>
		<bottom-tab-bar-com v-if="userInfo.userType === '03'" :tabIndexs="tabNum" :unRead="unRead" />
		<bottom-tab-bar v-else :tabIndexs="tabNum" :unRead="unRead" />

	</view>

</template>

<script>
import { unReadCount } from '@/api/message'

import { findServeIconListPerApp, findCarouselImageListCmpApp, findCarouselImageListPerApp, findServeIconListCmpApp, resumeExpect, jobberQuery, companyQuery, appMyPostList } from "@/api/index";

export default {
	data() {
		return {
			unRead: 0,
			region: '地区',
			loading: false,
			searchName: '',
			tabNum: 0,
			scrollPage: false,
			bgColor: 'transparent',
			girdHeight: 0,
			custom: null,
			baseUrl: getApp().globalData.baseUrl,
			headerHeight: 0, // 用于存储头部高度
			statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
			bannerList: [],
			menuList: [],
			jobTabs: [
				{
					professionName: '推荐'
				}
			],
			activeMainTab: 0,
			activeSubTab: 101,
			jobList: [],
			noteFlag: true,
			params: {
				pageNo: 1,
				pageSize: 6,
				isRecommend: 1

			},
			//

			currentCity: '南京',
			hasSelectedCity: false,
			currentBanner: 0,
			currentGridPage: 0,
			menuPages: [],
			filterParam: {},
			filterParamNum: 0,
			// 企业端
			positionTabs: [],
			activeMainPTab: 0,
			paramsCom: {
				pageNo: 1,
				pageSize: 6,
				isRecommend: 1


			},
			loadList: false,
			personList: [],
			noteComFlag: true,
			subsidyList: [
				{
					title: '补贴申领',
					bgColor: '#DCFCE6',
					color: '#4FA57F',
					url: '/pages/index/subsidy'
				},
				{
					title: '政策解读',
					bgColor: '#E7F1FF',
					color: '#4476AF',
					url: '/pages/index/policy'
				},
				{
					title: '法务讲堂',
					bgColor: '#FFF3EC',
					color: '#DF7C4A',
					url: '/pages/index/legal'
				},
				{
					title: '财务贴士',
					bgColor: '#EFECFF',
					color: '#5145AC',
					url: '/pages/index/finance'
				},
			]
		};
	},

	computed: {
		userInfo() {
			console.log(this.$store.getters.userInfo)
			return this.$store.getters.userInfo || {};
		},

		currentMainTabObj() {
			return this.jobTabs.find(tab => tab.id === this.activeMainTab) || {};
		}
	},
	onPageScroll(e) {
		if (e.scrollTop > 3) {
			this.bgColor = '#fff'
			this.scrollPage = true
		} else {
			this.bgColor = 'transparent'
			this.scrollPage = false
		}
	},
	async onLoad() {



		this.custom = wx.getMenuButtonBoundingClientRect()

	},
	async onShow() {
		this.loadList = false
		this.menuPages = []
		await this.getBannerList()
		await this.getServeIconList()
		let _this = this;
		setTimeout(() => {
			const query = uni.createSelectorQuery();
			query.select('.grid').boundingClientRect(function (rect) {

				_this.girdHeight = rect.height
			}).exec();
		}, 200);
		this.tabNum = 0
		this.$forceUpdate()
		if (this.userInfo.userType === '03') {
			Object.assign(this.paramsCom, this.filterParam)
			console.log(this.paramsCom)
			this.paramsCom.pageNo = 1
			await this.getPersonList()
			this.loading = true

		} else {
			Object.assign(this.params, this.filterParam)
			this.params.pageNo = 1
			await this.getJobList()
			this.loading = true

		}
		if (this.userInfo && this.userInfo.userType) {
			if (this.userInfo.userType === '03') {
				await this.getPositionList()
			} else {
				await this.getResumeList()

			}
			await this.getUnReadCount()
		}

	},

	onReachBottom() {
		if (this.userInfo.userType === '03') {
			this.paramsCom.pageNo++;
			if (this.noteComFlag) {
				this.getPersonList();
			}
		} else {
			this.params.pageNo++;
			if (this.noteFlag) {
				this.getJobList();
			}

		}


	},
	methods: {
		async changeRegion(e) {
			this.region = e.detail.value[1]
			if (this.userInfo.userType === '03') {
				this.paramsCom.cityCode = e.detail.code[1]
				this.getPersonList();

			} else {
				this.params.cityCode = e.detail.code[1]
				this.getJobList();
			}


		},
		async getUnReadCount() {
			const { data } = await unReadCount()
			getApp().globalData.unReadCount = data
			this.unRead = data
		},
		// 切换身份
		async toggleRole(type) {
			if (this.userInfo.userId) {
				uni.navigateTo({ url: `/pages/index/load?userType=${type}` })
			} else {
				uni.showModal({
					title: '提示',
					content: '你还未登录是否去登录？',
					confirmColor: '#37AF71',
					success: async function (res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/login/login'
							})
						} else if (res.cancel) {

						}
					}
				});
			}



		},
		// 搜索
		toSearch() {
			if (!this.searchName) {
				uni.showToast({ title: '请输入搜索内容', icon: 'none' })
				return false;
			}
			uni.navigateTo({
				url: `/pages/index/search?searchKey=${this.searchName}`
			})
		},
		// 个人端——补贴申领
		goSubsidy() {
			uni.navigateTo({
				url: '/pages/index/subsidy'
			})
		},
		// 补贴申领
		goUrl(item) {
			uni.navigateTo({
				url: item.url
			})
		},
		// 获取首页轮播图
		async getBannerList() {
			let api = this.userInfo.userType === '03' ? findCarouselImageListCmpApp : findCarouselImageListPerApp;
			const {
				data
			} = await api();
			this.bannerList = data
		},
		// 获取推荐服务列表
		async getServeIconList() {
			let api = this.userInfo.userType === '03' ? findServeIconListCmpApp : findServeIconListPerApp;
			const {
				data
			} = await api();
			this.menuList = data
			await this.menuPage()

		},
		// 获取期望职位列表
		async getResumeList() {
			const {
				data
			} = await resumeExpect();
			data.unshift({
				professionName: '推荐'
			})
			this.jobTabs = data
		},
		// 获取招聘职位列表
		async getPositionList() {
			const {
				rows
			} = await appMyPostList();
			rows.unshift({
				professionName: '推荐牛人'
			})
			this.positionTabs = rows

		},
		// 获取职位列表
		async getJobList() {
			this.loadList = false
			const {
				rows
			} = await jobberQuery(this.params);
			if (rows.length < this.params.pageSize) {
				this.noteFlag = false
			}
			this.jobList = this.params.pageNo === 1 ? rows : [...this.jobList, ...rows];
			if (this.jobList.length < 1) {
				this.loadList = true
			}
		},
		// 获取牛人列表
		async getPersonList() {
			this.loadList = false
			const {
				rows
			} = await companyQuery(this.paramsCom);
			if (rows.length < this.paramsCom.pageSize) {
				this.noteComFlag = false
			}
			this.personList = this.paramsCom.pageNo === 1 ? rows : [...this.personList, ...rows];
			if (this.personList.length < 1) {
				this.loadList = true
			}

		},
		// 跳转到筛选页面
		filterBtn() {
			if (this.userInfo.userType === '03') {
				uni.navigateTo({
					url: `/pages/index/filterCom?filterP=${JSON.stringify(this.filterParam)}`
				})
			} else {
				uni.navigateTo({
					url: `/pages/index/filter?filterP=${JSON.stringify(this.filterParam)}`
				})

			}

		},
		// 跳转服务详情
		goDetail(type, item) {
			console.log(item)
			let id = ''
			if (type === 'banner') id = item.linkId
			if (type === 'serve') id = item.serveId
			uni.navigateTo({
				url: `/pages/service/serviceDetail?serveId=${id}`
			})

		},
		// 跳转职位详情
		goJobDetail(item) {

			uni.navigateTo({
				url: `/pages/position/detail?positionId=${item.positionId}`
			})
		},
		goPersonDetail(item) {
			// uni.navigateTo({
			// 	url: `/pages/position/resume?userId=${item.userId}`
			// })
			if (this.userInfo.companyId) {
				uni.navigateTo({
					url: `/pages/position/resume?userId=${item.userId}`
				})
			} else {
				uni.showModal({
					title: '提示',
					content: '你还未认证企业是否去认证？',
					confirmColor: '#37AF71',
					success: async function (res) {
						if (res.confirm) {
							uni.navigateTo({
								url: '/pages/auth/companyAuth'
							})
						} else if (res.cancel) {

						}
					}
				});
			}

		},
		menuPage() {
			const pages = [];
			const pageSize = 15; // 每页15个图标, 3行5列
			for (let i = 0; i < this.menuList.length; i += pageSize) {
				pages.push(this.menuList.slice(i, i + pageSize));
			}
			this.menuPages = pages
		},
		goSelectCity() {
			uni.navigateTo({
				url: '/pages/selectCity/selectCity'
			});
		},
		getCurrentLocationCity() {
			const that = this;
			uni.getLocation({
				type: 'wgs84',
				success: function (res) {
					// 这里调用第三方逆地理编码API获取城市名
					// 以高德地图为例：
					// const key = '你的高德Key';
					// uni.request({
					//   url: `https://restapi.amap.com/v3/geocode/regeo?location=${res.longitude},${res.latitude}&key=${key}`,
					//   success: function(resp) {
					//     const city = resp.data.regeocode.addressComponent.city || resp.data.regeocode.addressComponent.province;
					//     that.currentCity = city;
					//   }
					// });
					// 这里只做演示，默认写死"定位城市"
					if (!that.hasSelectedCity) {
						that.currentCity = '定位城市';
					}
				},
				fail: function () {
					if (!that.hasSelectedCity) {
						that.currentCity = '定位失败';
					}
				}
			});
		},
		selectMainTab(tab, index) {
			console.log(tab)
			this.activeMainTab = index;
			if (this.userInfo.userType === '03') {
				if (index === 0) {
					this.paramsCom.isRecommend = 1
					this.paramsCom.professionId = null
				} else {
					this.paramsCom.isRecommend = ''
					this.paramsCom.professionId = tab.professionId ? tab.professionId : null
				}

				this.paramsCom.pageNo = 1
				this.getPersonList()
			} else {
				if (index === 0) {
					this.params.isRecommend = 1
				} else {
					this.params.isRecommend = ''
				}
				this.params.professionIdList = tab.professionId ? [tab.professionId] : []
				this.params.pageNo = 1
				this.getJobList()
			}

		},
		selectSubTab(subTabId) {
			this.activeSubTab = subTabId;
		},
		onBannerChange(e) {
			this.currentBanner = e.detail.current;
		},
		onGridChange(e) {
			this.currentGridPage = e.detail.current;
		},
	}
};
</script>

<style lang="less" scoped>
@import url(home.less);
</style>